import { Injectable } from '@nestjs/common';

declare const module: any;

@Injectable()
export class ConfigService {
  // 是否热重载模式
  readonly isHot = Boolean(module.hot);

  // 环境变量
  private env: any;

  constructor() {
    if (this.isHot) {
      this.env = require('../env/config.dev.env.ts');
    } else {
      this.env = require('../env/config.prod.env.ts');
    }
  }

  // jwt 密钥
  get jwtSecret() {
    return this.env.jwtSecret;
  }

  //  MongoDB 连接 URL
  get mongodbURI() {
    return this.toMongoURI(
      this.env.mongo.host,
      this.env.mongo.port,
      this.env.mongo.db,
      {
        username: this.env.mongo.initdb.username,
        password: this.env.mongo.initdb.password,
      },
    );
  }

  /**
   * 转换成 MongoDB 的连接 URL
   * @param host 主机
   * @param port 端口
   * @param db 数据库
   * @param options 选项
   */
  private toMongoURI(
    host: string,
    port: string,
    db: string,
    options?: {
      username: string;
      password: string;
      authSource?: string;
    },
  ): string {
    // 如果数据库不需要认证
    if (undefined === options) {
      return `mongodb://${host}:${port}/${db}`;
    }
    return `mongodb://${options.username}:${
      options.password
    }@${host}:${port}/${db}?authSource=${
      options.authSource ? options.authSource : 'admin'
    }`;
  }

  // 微信小程序配置
  get weChat() {
    return this.env.weChat as {
      appid: string;
      secret: string;
      grant_type: string;
      code2SessionURL: string;
    };
  }
}
